package com.jy.task.fileoper;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;

import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.mssmb2.SMB2CreateDisposition;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.SmbConfig;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.share.File;
import com.jy.common.utils.base.Tools;
import com.jy.common.utils.base.UuidUtil;
import com.jy.entity.filemanager.TSFile;

/**
 * SMB2连接示例 例: 我们当前要连接 IP为:123.123.123.123 目录为: SRC/SMB2/ 下的文件
 * 
 * @author yuanqi
 * 
 */
public class SMB1Connect {

	private String remoteUrlStr;
	private String localDirStr;
	private List<TSFile> fileStr;
	private String fileName;// 文件名
	private String extenName;// 扩展名
	private Date startDate;
	private Integer isSubFile;// 是否包含子文件夾
	private DiskShare share1;
	private Date newDate = null;// 最新文件时间

	public SMB1Connect(String remoteUrl, String localDir, String fileName,
			String extenName, Date startDate, Integer isSubFile) {
		this.remoteUrlStr = remoteUrl;
		this.localDirStr = localDir;
		fileStr = new ArrayList<TSFile>();
		this.fileName = fileName;
		this.extenName = extenName;
		this.startDate = startDate;
		this.isSubFile = isSubFile;
	}

	public boolean smbToSmbDirectory(String remoteUrl, String localDir,
			Integer type) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		boolean result = true;
		try {
			SmbFile smbFile = new SmbFile(remoteUrl);
			if (!smbFile.exists()) {
				System.out.println("no such folder");
			} else {
				SmbFile[] files = smbFile.listFiles();
				for (SmbFile f : files) {
					if (!f.isDirectory()) {
						String dateTime = simpleDateFormat.format(new Date(f
								.getDate()));
						setNewDate(simpleDateFormat.parse(dateTime));
						// 文件時間是否在规定范围
						if (compareToDate(simpleDateFormat.parse(dateTime),
								simpleDateFormat.parse(simpleDateFormat
										.format(this.startDate)))) {
							// 扩展名和名称
							if (Tools.isEmpty(this.fileName)) {
								result = smbTosmb(f, localDir, type);
							} else {
								if (patternStr(f.getName())) {
									result = smbTosmb(f, localDir, type);
								}
							}
						}
					} else {
						if (this.isSubFile == 1) {
							if (type == 1) {
								result = smbTosmb(f, localDir, type);
							} else if (type == 2) {
								if (!share1.folderExists(localDir)) {
									share1.mkdir(localDir);
								}
							}
							smbToSmbDirectory(remoteUrl + f.getName(), localDir
									+ f.getName(), type);

						}
					}

				}
			}
		} catch (Exception e) {
			result = false;
			e.printStackTrace();

		} finally {

		}
		return result;
	}

	private boolean patternStr(String str) {
		String newString[] = (this.fileName).split(",");
		boolean rs = false;
		for (String reg : newString) {
			String regEx = reg.replace(".", "/").replace("?", ".?")
					.replace("*", ".*");
			Pattern pattern = Pattern.compile(regEx);
			Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
			Matcher matcher = pattern.matcher(str);
			rs = matcher.find();
			if (rs)
				break;
		}
		// 查找字符串中是否有匹配正则表达式的字符/字符串
		return rs;
	}

	private void setNewDate(Date dateStr) {
		if (newDate != null) {
			if (compareToDate(dateStr, newDate)) {
				newDate = dateStr;
			}
		} else {
			newDate = dateStr;
		}
	}

	public Date getNewDate() {
		return newDate;
	}

	private boolean compareToDate(Date date1, Date date2) {
		if (date1.getTime() > date2.getTime()) {
			return true;
		}
		return false;
	}

	// private boolean getExFileName(SmbFile f, String localDirNew,Integer type)
	// {
	// boolean retsult = true;
	// if (Tools.isEmpty(this.extenName)) {
	// if(type==1){
	// retsult = smbTosmb(f, localDirNew);
	// }
	// else{
	//
	// }
	// } else {
	// if (f.getName().contains(this.extenName)) {
	// if(type==1){
	// retsult = smbTosmb(f, localDirNew);
	// }
	// }
	// }
	// return retsult;
	// }

	/**
	 * 
	 * @param smbFile
	 *            文件file
	 * @param remoteUrl
	 *            目标路径
	 */
	public boolean smbTosmb(SmbFile smbFile, String remoteUrl, Integer type) {
		SmbFileInputStream in = null;
		SmbFileOutputStream out = null;
		OutputStream outStr = null;
		boolean result = true;
		try {
			System.out.println(type + "???" + remoteUrl + smbFile.getName());
			if (!smbFile.isDirectory()) {
				in = new SmbFileInputStream(smbFile);
				int length = smbFile.getContentLength();// 得到文件的大小
				byte[] buffer = new byte[length + 1];
				if (type == 1) {
					SmbFile remoteFile = new SmbFile(remoteUrl
							+ smbFile.getName());
					remoteFile.connect();
					out = new SmbFileOutputStream(remoteFile);
					while (in.read(buffer) != -1) {
						out.write(buffer);
						// buffer = new byte[1024];
					}
					out.flush();
				} else if (type == 2) {
					File smbFileRead1 = share1.openFile(
							remoteUrl + smbFile.getName(),
							EnumSet.of(AccessMask.GENERIC_WRITE), null,
							SMB2ShareAccess.ALL,
							SMB2CreateDisposition.FILE_OVERWRITE_IF, null);
					outStr = smbFileRead1.getOutputStream();
					int len = 0;
					while ((len = in.read(buffer, 0, buffer.length)) != -1) {
						outStr.write(buffer, 0, len);
					}
					outStr.flush();
				}
				TSFile objFile = new TSFile();
				objFile.setId(UuidUtil.get32UUID());
				objFile.setFileName(smbFile.getName());
				fileStr.add(objFile);

			} else {
				SmbFile remoteFile1 = new SmbFile(remoteUrl + smbFile.getName());
				remoteFile1.connect();
				if (!remoteFile1.exists()) {
					remoteFile1.mkdir();
				}
			}

		} catch (Exception e) {
			result = false;
			e.printStackTrace();

		} finally {
			try {
				if (!smbFile.isDirectory()) {
					in.close();
				}
			} catch (IOException e) {

				e.printStackTrace();

			}
		}
		return result;
	}

	public boolean smbTosmbMother() {
		boolean result = smbToSmbDirectory(this.remoteUrlStr, this.localDirStr,
				1);
		if (!result)
			newDate = null;
		return result;
	}

	public boolean smbTosmb2Month(String ipNew, String userNamNew,
			String pswNew, String newFilePath, String toPath) {
		boolean result = false;
		SmbConfig config = SmbConfig.builder()
				.withTimeout(12000, TimeUnit.SECONDS)
				.withTimeout(12000, TimeUnit.SECONDS) // 超时设置读，写和Transact超时（默认为60秒）
				.withSoTimeout(18000, TimeUnit.SECONDS) // Socket超时（默认为0秒）
				.build();
		// 如果不设置超时时间 SMBClient client = new SMBClient();
		SMBClient client = new SMBClient(config);
		Connection connection1;
		try {
			connection1 = client.connect(ipNew);
			AuthenticationContext ac = new AuthenticationContext(userNamNew,
					pswNew.toCharArray(), ipNew);
			Session session = connection1.authenticate(ac);
			share1 = (DiskShare) session.connectShare(newFilePath);
			if (share1.isConnected()) {
				result = true;
				result = smbToSmbDirectory(this.remoteUrlStr, toPath, 2);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			newDate = null;
			return false;
		}
		if (!result)
			newDate = null;
		return result;
	}

	public List<TSFile> getresultFIle() {
		return fileStr;
	}

	public void main(String[] args) throws IOException {

		String string = "111";
		System.out.println(string.split(","));
		/*
		 * smbToSmbDirectory(
		 * "smb://administrator:CloudBim_403@192.168.0.13/test/name/",
		 * "smb://administrator:CloudBim_403@192.168.0.13/test/new/");
		 */
	}

}
